package com.yy.auth.server.config.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Enumeration;

/**
 * @Description 令牌端点日志过滤器
 * @Date 2025/10/11 上午9:35
 * @Author yanglin
 **/
@Component
public class TokenEndpointLogFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(TokenEndpointLogFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        logger.debug("[SSO-AUTH-SERVER-TOKEN] request url : {}", request.getRequestURI());
        if (request.getRequestURI().endsWith("/oauth2/token")) {
            logger.debug("[SSO-AUTH-SERVER-TOKEN] Token endpoint request received");
            logger.debug("[SSO-AUTH-SERVER-TOKEN] Method: {}", request.getMethod());
            logger.debug("[SSO-AUTH-SERVER-TOKEN] Content-Type: {}", request.getContentType());

            // 记录请求头
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                logger.debug("[SSO-AUTH-SERVER-TOKEN] Header: {} = {}", headerName, request.getHeader(headerName));
            }

            // 记录请求参数
            request.getParameterMap().forEach((key, values) -> {
                logger.debug("[SSO-AUTH-SERVER-TOKEN] Parameter: {} = {}", key, String.join(",", values));
            });
        }
        filterChain.doFilter(request, response);
    }
}
